package com.niuxiaofa.newlaw.Activity;

import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.niuxiaofa.newlaw.Base.BaseActivity;
import com.niuxiaofa.newlaw.Bean.BaseBean;
import com.niuxiaofa.newlaw.Network.ApiService;
import com.niuxiaofa.newlaw.Network.PublicPresenter;
import com.niuxiaofa.newlaw.Network.ServiceManager;
import com.niuxiaofa.newlaw.R;
import com.niuxiaofa.newlaw.Tools.ActivityUtil;
import com.niuxiaofa.newlaw.Tools.GetLog;
import com.niuxiaofa.newlaw.Tools.GlideEngine;
import com.niuxiaofa.newlaw.Tools.LogUtil;
import com.niuxiaofa.newlaw.Tools.UIUtils;
import com.niuxiaofa.newlaw.View.DownloadDialog;
import com.niuxiaofa.newlaw.adapter.SelectImageAdapter;
import com.niuxiaofa.newlaw.videoupload.TXUGCPublish;
import com.niuxiaofa.newlaw.videoupload.TXUGCPublishTypeDef;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import www.linwg.org.lib.LCardView;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/*
发表动态
 */
public class PublishDynamicActivity extends BaseActivity {

    List<LocalMedia> selectListPicList = new ArrayList<>();
    SelectImageAdapter selectImageAdapter;
    @BindView(R.id.selectImage)
    RecyclerView selectImage;
    private LocalMedia localMedia;
    String flimg;
    String key = "";
    int current = 0;
    TXUGCPublish mVideoPublish;
    String type;

    @BindView(R.id.content)
    EditText content;

    @BindView(R.id.send)
    LCardView send;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish_dynamic;
    }

    @Override
    protected void initData() {

        PublicPresenter.getUploadSignature(new PublicPresenter.interface_getUploadSignature() {
            @Override
            public void getResponse(BaseBean u) {

                key = u.getData().toString();

            }
        });

        type = getIntent().getStringExtra("type");


        selectImage.setLayoutManager(new GridLayoutManager(PublishDynamicActivity.this, 3));
        selectImageAdapter = new SelectImageAdapter(selectListPicList, type == null ? false : true);
        selectImageAdapter.setOnItemClickListener(new SelectImageAdapter.OnItemClickListener() {


            @Override
            public void onTakePhotoClick() {
                PictureSelector.create(UIUtils.getActivity())
                        .openGallery(type != null ? PictureMimeType.ofVideo() : PictureMimeType.ofImage())
                        .maxSelectNum(type != null ? 1 : 6)
                        .theme(R.style.picture_my_style)
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .forResult(CHOOSE_REQUEST);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }

            @Override
            public void onDeleteItemClick(int position) {
                selectListPicList.remove(position);
                selectImageAdapter.notifyDataSetChanged();
            }
        });

        selectImage.setAdapter(selectImageAdapter);

        send.setOnClickListener(e -> {

            Map map = new HashMap();
            map.put("content", content.getText().toString());
            map.put("picture", "");
            map.put("permissions", "");
            map.put("exclude", "");
            Gson gson = new Gson();
            String json = gson.toJson(map);

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

            Call<BaseBean> call = ServiceManager.getInstance().creat(ApiService.class).member(body);
            call.enqueue(new Callback<BaseBean>() {
                @Override
                public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                    //判断请求是否成功
                    if (response.isSuccessful()) {
                        BaseBean baseBean = (BaseBean) response.body();
                        Toast(baseBean.getMsg());
                        ActivityUtil.getInstance().finishCurrentActivity();
                    }
                }

                @Override
                public void onFailure(Call<BaseBean> call, Throwable t) {
//            Log.e("链接错误", t.getMessage());
                    Toast.makeText(UIUtils.getActivity(), "网络连接异常,请稍候在试", Toast.LENGTH_LONG).show();
                }
            });

        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    if (type != null) {
                        uplodevideo(data);
                    } else {
                        selectPic(data);
                    }
                    break;
            }


        }
    }

    void selectPic(Intent data) {
        // 图片选择结果回调
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        for (LocalMedia media : selectList) {
            LogUtil.e("获取图片路径成功:" + media.getPath());
            if (Build.VERSION.SDK_INT >= 29) {
                media.setPath(media.getRealPath());
            }
            localMedia = media;
        }

        // 图片选择结果回调
        flimg = "";
        selectListPicList.clear();
        selectListPicList.addAll(selectList);
        //  imglength.setText("上传图片(" + selectListPic.size() + "/3)");

        selectImageAdapter.notifyDataSetChanged();
    }

    void uplodevideo(Intent data) {
        List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
        for (LocalMedia media : selectListPic) {
            LogUtil.e("获取图片路径成功:" + media.getPath());

            if (Build.VERSION.SDK_INT >= 29) {
                media.setPath(media.getRealPath());
            }


            mVideoPublish = new TXUGCPublish(this.getApplicationContext(), "independence_android");
            TXUGCPublishTypeDef.TXPublishParam param = new TXUGCPublishTypeDef.TXPublishParam();
            param.signature = key;
            param.coverPath = getVideoThumbnail(media.getPath());
            param.videoPath = media.getPath();
            int publishCode = mVideoPublish.publishVideo(param);

            GetLog.getLog("publishCode=" + publishCode + "");
            mVideoPublish.setListener(new TXUGCPublishTypeDef.ITXVideoPublishListener() {

                DownloadDialog downloadDialog = new DownloadDialog(UIUtils.getActivity());


                @Override
                public void onPublishProgress(long uploadBytes, long totalBytes) {
                    //   mProgress.setProgress((int) (100*uploadBytes/totalBytes));

                    GetLog.getLog("current=" + current + "");
                    downloadDialog.setcurrent(current);
                    downloadDialog.show();
                    current = (int) (100 * uploadBytes / totalBytes);
                }

                @Override
                public void onPublishComplete(TXUGCPublishTypeDef.TXPublishResult result) {
                    //  mResultMsg.setText();
                    selectListPic.clear();
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(result.coverURL);
                    selectListPicList.add(localMedia);
                    GetLog.getLog("TXPublishResult " + result.retCode + " Msg:" + (result.retCode == 0 ? result.videoURL : result.descMsg) + " coverURL " + result.coverURL);

                    downloadDialog.dismiss();

                    selectImageAdapter.notifyDataSetChanged();
                }
            });

        }

    }

    public static String getVideoThumbnail(String url) {

        Bitmap bitmap = null;

        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一的接口，用于从输入的媒体文件中取得帧和元数据；


        MediaMetadataRetriever media = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图


            media.setDataSource(url);// videoPath 本地视频的路径
            //获得第一帧图片

            bitmap = media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

            FileOutputStream fos;
            String imagePath = "";
            try { // 判断手机设备是否有SD卡
                boolean isHasSDCard = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                if (isHasSDCard) { // SD卡根目录
                    ContextWrapper cw = new ContextWrapper(getContext());
                    File directory = cw.getExternalFilesDir(Environment.DIRECTORY_DCIM);
                    File file = new File(directory, Calendar.getInstance().getTimeInMillis() + ".png");
                    fos = new FileOutputStream(file);
                    imagePath = file.getAbsolutePath();
                    Log.e("imagePath", imagePath);

                    //   Toast("图片保存成功" + imagePath);

                } else {
                    throw new Exception("创建文件失败!");
                }

                bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                fos.flush();
                fos.close();
            } catch (IllegalArgumentException | FileNotFoundException e) {

                e.printStackTrace();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return imagePath;
        } finally {
            media.release();
        }

    }

}
